<script>
	import config from '@/config.js'
	import store from '@/store';
	import {
		checkLogin,
		isVIP
	} from '@/utils/util.js' ;
	import {origin} from '@/config.js'
	import {mapState} from "vuex"
	import loginApi from "@/api/userInfo.js"
	export default {
		// 全局变量
		globalData: {
			systemInfo: {},
			payBtnText: '由于相关规范, iOS功能暂不可用',
			envVersion: '',
			system: ''
		},
		onShow(options) {
			
		},
		onLaunch: async function (options) {
			// #ifdef MP-WEIXIN
			let startParamObj = uni.getLaunchOptionsSync();
			if (startParamObj.scene != 1154) {
				// 微信朋友圈单页模式不支持热更新api
				this.updateManager();
			}
			// #endif
			const version = uni.getStorageSync('version'),
						currentVersion = '0.1.0';
			if (version) {
				if (version == currentVersion) {

				} else {
					this.$store.dispatch('Logout')
					uni.setStorageSync('version', currentVersion);
				}
			} else {
				this.$store.dispatch('Logout')
				uni.setStorageSync('version', currentVersion);
			}
			this.getSystemInfo()
			if(checkLogin()) {
				this.getUserBrief()
			}
			
		},
		methods: {
			getSystemInfo() {
				const that = this;
				// #ifdef MP-WEIXIN
				let environment = uni.getAccountInfoSync()
				that.globalData.envVersion = environment.miniProgram.envVersion;
				// #endif
				// #ifdef MP-TOUTIAO || MP-BAIDU
				let environment = uni.getEnvInfoSync()
				let envVersion = environment.env || environment.microapp.envType;
				if (envVersion === 'production') {
					envVersion = 'release'
				}
				if (envVersion === 'preview') {
					envVersion = 'develop'
				}
				that.globalData.envVersion = envVersion;
				// #endif
				uni.getSystemInfo({
					success: res => {
						console.log('systemInfo', res)
						let systemInfo = res;
						// #ifdef MP-TOUTIAO|| MP-BAIDU || MP-DINGTALK
						res.hideBackIcon = true;
						// #endif
						store.commit("SET_SYSTEMTNFOS", systemInfo);
						// 状态栏高度
						store.commit("SET_NAVIGATION_CUSTOM_STATUS_HEIGHT", systemInfo.statusBarHeight);
						systemInfo.isPC = false;
						if ((systemInfo.platform.toLowerCase().indexOf('win') == 0) || (systemInfo.platform
								.toLowerCase().indexOf('mac') == 0) || (systemInfo.platform.toLowerCase()
								.indexOf('linux') == 0)) {
							systemInfo.isPC = true
						}
						if (systemInfo.system.toLowerCase().indexOf('ios') > -1) {
							systemInfo.system = 'ios';
						} else {
							systemInfo.system = 'android';
						}
						// 手机系统 安卓 or iPhone
						store.commit("SET_TYPE", systemInfo.system);
						this.$store.commit("SET_SYSTEMINFO", systemInfo)
						that.calculateNavigationHeight();
					}
				});
			},
			getUserBrief() {
				loginApi.getUserBrief(true)
			},
			/**
			 * 小程序主动更新
			 */
			updateManager() {
				const updateManager = uni.getUpdateManager();
				updateManager.onCheckForUpdate(res => {
					// 请求完新版本信息的回调
				})
				updateManager.onUpdateReady(() => {
					uni.showModal({
						title: '更新提示',
						content: '新版本已经准备好，即将重启应用',
						showCancel: false,
						success(res) {
							if (res.confirm) {
								// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
								updateManager.applyUpdate()
							}
						}
					})
				})
				updateManager.onUpdateFailed(() => {
					// 新的版本下载失败
					uni.showModal({
						title: '更新提示',
						content: '新版本下载失败',
						showCancel: false
					})
				})
			},
			calculateNavigationHeight() {
				const systemInfo = store.state.system
				const that = this;
				var navigationCustomCapsuleHeight = 44;
				var navigationCustomStatusHeight = systemInfo.navigationCustomStatusHeight;
				// 标题栏高度
				store.commit("SET_NAVIGATION_CUSTOM_CAPSULE_HEIGHT", navigationCustomCapsuleHeight);
				// 导航栏总高度
				store.commit(
					"SET_NAVIGATION_HEIGHT",
					navigationCustomCapsuleHeight + navigationCustomStatusHeight
				)
			},
			// 获取路由配置V2
			async MiniAppRouteConfigV2(url, isCloseCurrentPage=false) {
				let toUrl, isWhiteListFlag = true,
					isMatch = false;
			 let MiniAppRouteConfigV2 = uni.getStorageSync('MiniAppRouteConfigV2')
				if (MiniAppRouteConfigV2.whiteList.length) {
					isWhiteListFlag = MiniAppRouteConfigV2.whiteList.some(ele => {
						return url.indexOf(ele.value) != -1
					})
				}
				if (isWhiteListFlag) {
					if (MiniAppRouteConfigV2.config.length) {
						for (let i = 0; i < MiniAppRouteConfigV2.config.length; i++) {
							let regxStr = MiniAppRouteConfigV2.config[i].regex;
							let reg = new RegExp(regxStr)
							if (reg.test(url)) {
								isMatch = true;
								let paramsArr = reg.exec(url);
								toUrl = `${MiniAppRouteConfigV2.config[i].appRoute}`;
								// 院校需要用numid换取code
								if (MiniAppRouteConfigV2.config[i].remark == '院校') {
									if (paramsArr[1].length != 5) {
										let res = await queryCollegesCode(
											`youzy.dms.basiclib.api.college.bynumid.get?numId=${paramsArr[1]}`)
										if (res.isSuccess && res.result.code) {
											paramsArr[1] = res.result.code;
										}
									}
								}
								if(MiniAppRouteConfigV2.config[i].remark == '外链'){
									paramsArr[1] = decodeURIComponent(url.split('url=')[1]);
								}
								if (MiniAppRouteConfigV2.config[i].group != -1) {
									toUrl += `?${MiniAppRouteConfigV2.config[i].paramName}=${paramsArr[1]}`
								}
								// 多个参数
								if (MiniAppRouteConfigV2.config[i].group > 1) {
									for (let attr in MiniAppRouteConfigV2.config[i].moreParam) {
										toUrl += `&${attr}=${MiniAppRouteConfigV2.config[i].moreParam[attr]}`
									}
								}
								if (MiniAppRouteConfigV2.config[i].isTab) {
									uni.switchTab({
										url: toUrl,
									})
								} else {
									if(isCloseCurrentPage) {
										uni.redirectTo({
											url: toUrl,
											fail(err) {
												console.log('跳转失败', err)
											},
										})
									} else {
										uni.navigateTo({
											url: toUrl,
											fail(err) {
												console.log('跳转失败', err)
											},
										})
									}
								}
								return;
							}
						}
						if (!isMatch) {
							if (url.indexOf('.cn') != -1 || url.indexOf('.com') != -1) {
								if(isCloseCurrentPage) {
									uni.redirectTo({
										url: '/pages/webPage/index?url=' + encodeURIComponent(url),
									})
								} else {
									uni.navigateTo({
										url: '/pages/webPage/index?url=' + encodeURIComponent(url),
									})
								}
							}
						}
					}
				} else {
					if (url.indexOf('/pages/') !== -1 || url.indexOf('/packages/') !== -1) {
						uni.navigateTo({
							url
						})
					} else {
						uni.navigateTo({
							url: '/pages/transfer-tips/index?type=2&url=' + url
						})
					}
			    }
			  },

			/**
			 * 登录之后需要  做的操作
			 * @param {Object} userInfo
			 * @param {Object} collegeCodes
			 */
			async backHttpRequestRemote(userInfo, collegeCodes) {
				// TODO
			},
			// 适配各端获取高度
			/**
			 * @param {String} selector 元素CLASS or ID
			 * @param {String} type  空值 or all 空值默认查单个元素，all查所有(返回数剧格式不同)
			 */
			querySelectorHeight(selector, type) {
				if (!selector) return;
				let item = uni.createSelectorQuery();
				if (!type) {
					item.select(selector).boundingClientRect();
				} else {
					item.selectAll(selector).boundingClientRect();
				}
				let res = new Promise((resolve) => {
					item.exec(res => {
						resolve(res)
					})
				})
				return res
			},
			// 打开登录弹窗
			showLoginPopup() {
				store.commit('UPDATE_LOGIN_POPUP', true)
			},

			// 获取当前路由地址及参数，登录之后跳转回去
			saveCurrentPage() {
				const pages = getCurrentPages();
				const currentPage = pages[pages.length - 1];
				const shareUrl = currentPage.route;
				const shareOptions = currentPage.options;
				const sdata = [];
				if (!shareOptions.share) {
					shareOptions.share = true;
				}
				for (let attr in shareOptions) {
					sdata.push(`${attr}=${this.filter(shareOptions[attr])}`);
				}
				this.globalData.shareUrl = '/' + shareUrl + '?' + decodeURIComponent(sdata.join('&'));
				
			},
		},
	}
</script>
<style>
	@import url("./static/font/iconfont.css");
	@import url("@/common.css");
	@import url("@/udeitor.css");
	/*每个页面公共css */
	@font-face {
		font-family: Bebas;
		src: url("https://staticv3.youzy.cn/fonts/bebas.ttf");
	}
</style>
